import { useEffect, useState } from "react";
import {prompt} from "@/service";
import { RespDataType, getRoleDeptCustomDataScope, updateRoleDataScope } from "../../../api";

export const useDataAuth = (roleId: number, dataScope: number,) => {
  const [loading, setLoading] = useState(true);
  const [deptTree, setDeptTree] = useState<RealTreeNode[]>([]);
  const [selectedDataScope, setSelectedDataScope] = useState<number>(dataScope);
  const [selectedDeptIds, setSelectedDeptIds] = useState<number[]>([]);

  useEffect(() => {
    setLoading(true);
    // Promise.all([getRole(roleId), getRoleDeptCustomDataScope(roleId)]).then((resp) => {
    Promise.all([getRoleDeptCustomDataScope(roleId)]).then((resp) => {
      // const [ roleResp, dataScopeResp ] = resp;
      const [dataScopeResp] = resp;

      // setSelectedDataScope(roleResp.data.dataScope);
      setSelectedDeptIds(dataScopeResp.data.checkedKeys);
      setDeptTree(formatDeptTree(dataScopeResp.data.depts));
      setLoading(false);
    })
    // getRoleDeptCustomDataScope(roleId).then((resp) => {
    //     setSelectedDeptIds(resp.data.checkedKeys);
    //     setDeptTree(formatDeptTree(resp.data.depts));
    //     setLoading(false);
    // })
  }, [roleId]);

  const updateDataScope = (values: { dataScope: number, deptIds: number[] }, successCallback: Function, failedCallback: Function) => {
    updateRoleDataScope(roleId, values).then(() => {
      prompt.success("授权成功");
      successCallback();
    }).catch(() => failedCallback())
  }

  return { loading, deptTree, selectedDataScope, setSelectedDataScope, selectedDeptIds, setSelectedDeptIds, updateDataScope }
}

interface RealTreeNode {
  title: string;
  key: number;
  value: number;
  children: RealTreeNode[];
}

const formatDeptTree = (tree: RespDataType.RoleSelectedCustomDataScope["depts"]): RealTreeNode[] => {
  return tree.map((item) => ({
    title: item.deptName,
    value: item.deptId,
    key: item.deptId,
    children: formatDeptTree(item.children || []),
  }))
}
